package ljl.alg.jianzhioffer.round2;

public class _67_atoi {
    
    public int strToInt3(String str) {
        if (str == null) return 0;
        str = str.trim();
        if (str.length() == 0) return 0;
        int sign = str.charAt(0) == '-' ? -1 : 1;
        int start = str.charAt(0) == '-' || str.charAt(0) == '+' ? 1 : 0;
        long num = 0;
        int i = start;
        int n = str.length();
        while (i < n && Character.isDigit(str.charAt(i))) {
            int cur = str.charAt(i) - '0';
            // -1 ? num * 10 - cur < integer.min
            // 1 ? num * 10 - cur <= integer.min
            
            long newNum = num * 10 - cur;
            if (sign == -1 && newNum < Integer.MIN_VALUE || sign == 1 && newNum <= Integer.MIN_VALUE)
                return sign == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            num -= cur;
            i++;
        }
        return  sign * (int) -num;
    }
    
    // 看看路飞的
    /**
    * 毕竟不是自己写的 背错了好几处
    * */
    public int strToInt(String str) {
        int i = 0, sign = 1, BOUNDARY = Integer.MAX_VALUE / 10;
        int res = 0, len = str.length();
        while (i < len && str.charAt(i) == ' ') i++;
        if (i == len) return 0;
        if (str.charAt(i) == '-') sign = -1;
        if (str.charAt(i) == '-' || str.charAt(i) == '+') i++;
        for (int j = i; j < len; j++) {
            if (!Character.isDigit(str.charAt(j))) break;
            if (res > BOUNDARY || res == BOUNDARY && str.charAt(j) > '7')
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            res = res * 10 + str.charAt(j) - '0';
        }
        return res * sign;
    }
}
